import { useReducer } from 'react';

/**
 * 定义初始状态信息
 */
export interface IstateType {
  leftSelectKeys: string[];
  leftExpandedKeys: string[];
  leftAutoExpandParent: boolean;
  typeSelectRow: Record<string, any>;
  dicFlowSelectRow: Record<string, any>;
}

/**
 * 新增和编辑页面操作枚举
 * @LEFTSELECT_ROW 左侧树 选中的数据
 * @LEFTSELECT_KEYS 左侧树 选中的key
 * @LEFTEXPANDED_KEYS 左侧树 展开的节点 key
 * @LEFTAUTO_PARENT 左侧树 控制是否展开树节点
 * @CLEAR_RECEIVE  清空存入 数据
 *
 */
export enum IDesignActionEnum {
  LEFTSELECT_KEYS = 'leftSelectKeys',
  LEFTEXPANDED_KEYS = 'leftExpandedKeys',
  LEFTAUTO_PARENT = 'leftAutoExpandParent',
  TREETYPE_SELECTROW = 'typeSelectRow',
  TREEDIC_SELECTROW = 'dicFlowSelectRow',
  CLEAR_RECEIVE = 'clearAllReceive',
}

/**
 * 定义新增和编辑页面操作匹配
 * @type 操作类型
 * @payload 传递数据
 */
export interface IActionType {
  type: IDesignActionEnum;
  payload?: any;
}

export const useDesignManageReducer = () => {
  /** 初始化状态 */
  const initState: IstateType = {
    leftSelectKeys: [],
    leftExpandedKeys: [],
    leftAutoExpandParent: false,
    typeSelectRow: {},
    dicFlowSelectRow: {},
  };

  const designManageReducer = (state: IstateType, action: IActionType) => {
    switch (action?.type) {
      /**
       * 左侧字典选中
       */
      case IDesignActionEnum.TREEDIC_SELECTROW:
        return {
          ...state,
          dicFlowSelectRow: action?.payload,
        };

      /**
       * 左侧类型 选中 类型数据
       */
      case IDesignActionEnum.TREETYPE_SELECTROW:
        return {
          ...state,
          typeSelectRow: action?.payload,
        };

      /**
       * 左侧树选中的数据的key
       */
      case IDesignActionEnum.LEFTSELECT_KEYS:
        return {
          ...state,
          leftSelectKeys: action?.payload,
        };

      /**
       * 左侧树 展开节点 key
       */
      case IDesignActionEnum.LEFTEXPANDED_KEYS:
        return {
          ...state,
          leftExpandedKeys: action?.payload,
        };

      /**
       * 左侧树 控制是否展开节点
       */
      case IDesignActionEnum.LEFTAUTO_PARENT:
        return {
          ...state,
          leftAutoExpandParent: action?.payload,
        };

      /**
       *  清空已选数据
       */
      case IDesignActionEnum.CLEAR_RECEIVE:
        return {
          ...state,
          leftSelectRows: [],
          leftSelectKeys: [],
          leftExpandedKeys: [],
          leftAutoExpandParent: false,
        };

      default:
        return {
          ...state,
          ...initState,
        };
    }
  };

  const [state, designDispatch] = useReducer(designManageReducer, initState);

  return {
    ...state,
    designDispatch,
  };
};
